package com.tbw.service;

import com.tbw.NotFoundException;
import com.tbw.dao.TypeRespository;
import com.tbw.entity.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService{

    @Autowired
    private TypeRespository typeRespository;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRespository.save(type);
    }
    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRespository.getOne(id);
    }
    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRespository.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeRespository.findAll();
    }

    @Override
    public List<Type> listTypeTop(Integer size) {
        //創建排序對象,定義排序的方向為倒序,按照blog列表的size進行排序
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        //創建pageable對象,得到第一頁
        Pageable pageable = PageRequest.of(0, size, sort);
        return typeRespository.findTop(pageable);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type type1=typeRespository.getOne(id);
        if (type1==null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,type1);
        return typeRespository.save(type1);
    }
    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRespository.deleteById(id);
    }

    @Override
    public Type getTypeByName(String name) {
        return typeRespository.findByName(name);
    }
}
